package com.cnaaa.pay.controller;

import com.alibaba.fastjson.JSON;
import com.cnaaa.pay.entity.Trade;
import com.cnaaa.pay.service.AlipayService;
import com.cnaaa.pay.service.TradeService;
import com.cnaaa.pay.util.RequestParamUtil;
import com.cnaaa.pay.vo.alipay.AlipayReturnVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 2018/10/29 Create by 郭文梁
 * AlipayPageController
 * 支付宝也米娜控制器
 *
 * @author 郭文梁
 * @date 2018/10/29
 */
@Controller
@RequestMapping("/alipay-page")
@Slf4j
public class AlipayPageController {
    private static final String PAYMENT_SUCCESS = "payment-success";
    private static final String PAYMENT_FAIL = "payment-fail";
    private final AlipayService alipayService;
    private final TradeService tradeService;

    @Autowired
    public AlipayPageController(AlipayService alipayService, TradeService tradeService) {
        this.alipayService = alipayService;
        this.tradeService = tradeService;
    }

    /**
     * 支付宝回调地址
     *
     * @param request 请求
     * @param model   DataModel
     * @return 视图名称
     * @throws UnsupportedEncodingException 异常
     */
    @GetMapping("/return")
    public String onPayReturn(HttpServletRequest request, Map<String, Object> model) throws UnsupportedEncodingException {
        Map<String, String> params = RequestParamUtil.pretty(request.getParameterMap());
        boolean success = alipayService.checkReturnSign(params);
        if (success) {
            AlipayReturnVo returnVo = JSON.parseObject(JSON.toJSONString(params), AlipayReturnVo.class);
            Trade trade = tradeService.onPayReturn(returnVo);
            if (trade == null) {
                model.put("msg", "订单不存在或已关闭");
                return PAYMENT_FAIL;
            } else {
                model.put("trade", trade);
                return PAYMENT_SUCCESS;
            }
        } else {
            model.put("msg", "鉴权失败");
            return PAYMENT_FAIL;
        }
    }
}
